<script lang="ts" setup>
import { reactive, ref, shallowRef, onMounted, onActivated } from 'vue'
import { useMap } from '@/hooks/useMap'
import { useActivated } from '@/hooks/useActivated'
import { useRoute } from 'vue-router'
import SearchPlace from '@/components/map/SearchPlace.vue'
import bikeImg from '@/assets/map/bikeLocation/bike.png'
import { queryBike } from '@/api/bike'
import { queryBikeTableCol } from '@/api/bike/types/bike'
import { getToken } from '@/utils/cache/cookies'
import { LongBikeState } from '@/types/enum'
import { ElMessage } from 'element-plus'
defineOptions({
  name: 'LongBikeAMap'
})
const route = useRoute()
const params = reactive({
  bikeCode: route.query.bikeCode as string,
  type: route.query.type as LongBikeState,
  pageSize: Number(route.query.pageSize),
  pageNum: 1,
  storeId: route.query.storeId as string
})

const center = reactive({
  longtitude: 0,
  latitude: 0
})
const loading = ref<boolean>(false)
const isInit = ref<boolean>(false)
const mapContainer = ref<HTMLDivElement>()
const markers = shallowRef<AMap.LabelMarker[]>([])
const data = ref<queryBikeTableCol[]>()
const labelsLayer = shallowRef<AMap.LabelsLayer>()
const { map, auto, initAmap, getAddress, placeSearch } = useMap(mapContainer, [
  Number(center.longtitude),
  Number(center.latitude)
])
/** 地图初始化 */
const getIcon: () => AMap.LabelMarkerIconOptions = () => {
  return {
    type: 'image', //图标类型，现阶段只支持 image 类型
    image: bikeImg, //可访问的图片 URL
    size: [30, 30], //图片尺寸
    clipOrigin: [0, 0],
    clipSize: [59, 63]
  }
}
const getData = async () => {
  try {
    loading.value = true
    const res = await queryBike({
      ...params,
      token: getToken() ?? ''
    })
    if (res.statusCode === '0') {
      data.value = res.data.list
      handleCoverInit()
    } else {
      ElMessage.error('暂无数据')
    }
    loading.value = false
  } catch (error) {
    console.error(error)
  }
}
const handleCoverInit = () => {
  if (data.value!.length > 0) {
    const firstBike = data.value![0]
    center.longtitude = Number(firstBike.longtitude ?? 0)
    center.latitude = Number(firstBike.latitude ?? 0)
  }
  if (isInit.value && map.value) {
    if (labelsLayer.value) {
      labelsLayer.value.clear()
      map.value.removeLayer(labelsLayer.value)
      map.value.clearMap()
    }
    map.value?.setCenter([center.longtitude, center.latitude])
    labelsLayer.value = new AMap.LabelsLayer({
      zooms: [3, 20],
      zIndex: 1000,
      collision: false, //该层内标注是否避让
      allowCollision: true //不同标注层之间是否避让
    })

    map.value.add(labelsLayer.value)
    const normalMarker = new AMap.Marker({
      anchor: 'bottom-center',
      offset: [0, -63]
    })
    data.value?.forEach((point: any) => {
      const curData = {
        position: new AMap.LngLat(Number(point.longtitude) ?? 0, Number(point.latitude) ?? 0),
        icon: getIcon(),
        rank: 1,
        zIndex: 16
      }
      const labelMarker = new AMap.LabelMarker(curData)
      markers.value?.push(labelMarker)
      labelMarker.on('click', async (e: any) => {
        const position = e.data.data && e.data.data.position
        if (position) {
          const address: any = await getAddress(position[0], position[1])
          normalMarker.setContent(createContent(address))
          normalMarker.setPosition(position)
          map.value?.add(normalMarker)
        }
      })
    })
    labelsLayer.value.add(markers.value)
  }
}
const createContent = (address: string) => {
  return `<div class="map-infowindow_location">
                  <span>车辆位置:${address}</span>
              </div>
              `
}
onMounted(async () => {
  isInit.value = await initAmap()
  await getData()
})
/** 处理是否缓存 */
onActivated(() => {
  params.type = route.query.type as LongBikeState
  params.pageSize = Number(route.query.pageSize)
  params.bikeCode = route.query.bikeCode as string
  params.storeId = route.query.storeId as string
})
useActivated(
  params,
  { params },
  [
    { key: 'pageSize', path: 'params.pageSize' },
    { key: 'bikeCode', path: 'params.bikeCode' },
    { key: 'type', path: 'params.type' },
    { key: 'storeId', path: 'params.storeId' }
  ],
  getData,
  []
)
</script>

<template>
  <div class="xy-map-container">
    <div ref="mapContainer" id="map-container" v-loading="loading">
      <search-place :auto="auto" :map="map!" :place-search="placeSearch" />
    </div>
  </div>
</template>

<style scoped></style>
